package com.atguigu.service.Impl;

import com.atguigu.common.exception.YyghException;
import com.atguigu.common.utils.JwtHelper;
import com.atguigu.mapper.UserInfoMapper;
import com.atguigu.service.PatientService;
import com.atguigu.service.UserInfoService;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        String openid = loginVo.getOpenid();
        if (StringUtils.isEmpty(openid)) {
            //手机号+验证码
            return this.phoneAndCodeLogin(loginVo);
        } else {//微信用户绑定手机号
            return this.wxBundlePhone(loginVo);
        }

    }

    //微信登录
    private Map<String, Object> wxBundlePhone(LoginVo loginVo) {
        //绑定手机号
        //根据openid查询该微信用户
        //根据手机号查询该用户  如果不存在  直接 setPhone 如果手机号已经存在 将两条数据合并
        UserInfo userInfo_wx = this.selecwxByOpenId(loginVo.getOpenid());
        UserInfo userInfo_ph = this.selectUserByPhone(loginVo.getPhone());
        if (userInfo_ph == null) {
            userInfo_wx.setPhone(loginVo.getPhone());
            baseMapper.updateById(userInfo_wx);
        } else {
            //手机号已经存在  合并两条数据
            userInfo_wx.setName(userInfo_ph.getName());
            userInfo_wx.setCertificatesType(userInfo_ph.getCertificatesType());
            userInfo_wx.setCertificatesNo(userInfo_ph.getCertificatesNo());
            userInfo_wx.setCertificatesUrl(userInfo_ph.getCertificatesUrl());
            userInfo_wx.setAuthStatus(userInfo_ph.getAuthStatus());
            userInfo_wx.setPhone(userInfo_ph.getPhone());
            baseMapper.deleteById(userInfo_ph.getId());
            baseMapper.updateById(userInfo_wx);
        }
        return this.get(userInfo_wx);

    }

    //根据手机号取查询
    private UserInfo selectUserByPhone(String phone) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        return baseMapper.selectOne(queryWrapper);
    }

    private Map<String, Object> phoneAndCodeLogin(LoginVo loginVo) {
        //手机号和验证码是否为空
        //手机号 加验证码的登录逻辑
        //也面上输入手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //参数校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(20001, "手机号和验证码都不能为空");
        }
        //2 校验验证码
        String code_redis = redisTemplate.boundValueOps(phone).get();
        if (StringUtils.isEmpty(code_redis)) {
            throw new YyghException(20001, "请先获取验证码");
        }
        //2验证码是否正确
        if (!code.equalsIgnoreCase(code_redis)) {
            throw new YyghException(20001, "验证码错误");
        }
        //3判断用户是否是新用户 如果是新用户 就要进行注册（手机号是否存在）
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        //4新用户 直接注册
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setAuthStatus(0);// 认证状态 -未认证
            userInfo.setStatus(1); //正常状态
            userInfo.setCreateTime(new Date());
            userInfo.setUpdateTime(new Date());
            baseMapper.insert(userInfo);
        }
        //判断用户是否被锁定
        if (userInfo.getStatus() == 0) {
            throw new YyghException(20001, "该用户已经被锁定");
        }
        //返回封装值
        return this.get(userInfo);
    }

    private Map get(UserInfo userInfo) {
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
        }
        //令牌的获取
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        map.put("name", name);
        return map;
    }

    @Override
    public UserInfo selecwxByOpenId(String openid) {
        //从 userInfo里面查询微信用户
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        return userInfo;
    }

    //用户认证功能
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询 用户xinxi
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置用户信息
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        //认证状态-认证状态
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //进行数据更新
        baseMapper.updateById(userInfo);


    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //封装条件
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        if(userInfoQueryVo!=null){
            String keyword = userInfoQueryVo.getKeyword();//用户模糊查询
            Integer authStatus = userInfoQueryVo.getAuthStatus();//认证状态
            Integer status = userInfoQueryVo.getStatus();//用户状态
            String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();//开始时间
            String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();//结束时间
            if(!StringUtils.isEmpty(keyword)){
                queryWrapper.like("name",keyword);
            }
            if(!StringUtils.isEmpty(authStatus)){
                queryWrapper.eq("auth_status",authStatus);
            }
            if(!StringUtils.isEmpty(status)){
                queryWrapper.eq("status",status);
            }

            if(!StringUtils.isEmpty(createTimeBegin)){
                queryWrapper.ge("create_time",createTimeBegin);
            }
            if(!StringUtils.isEmpty(createTimeEnd)){
                queryWrapper.le("create_time",createTimeEnd);
            }
            this.page(pageParam,queryWrapper);
            pageParam.getRecords().forEach(userInfo -> {
                this.packUserInfo(userInfo);
            });
        }
        return pageParam;
    }
     //用户状态锁定
    @Override
    public void lock(Long userId, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            this.updateById(userInfo);
        }
    }
    //用户详情
     @Autowired
     private PatientService  patientService;
    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> map =new HashMap<>();
        //根据 userId查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        this.packUserInfo(userInfo);
        map.put("userInfo",userInfo);
        //根据userId来查询就诊人信息
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findListByUserId(userId);
        map.put("patientList",patientList);
        return map;
    }
      //、用户认证审批接口
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    private void packUserInfo(UserInfo userInfo) {
        Integer status = userInfo.getStatus();//用户状态
        Integer authStatus = userInfo.getAuthStatus();//认证状态
        String statusString = status==0?"锁定":"正常";
        String authStatusString = AuthStatusEnum.getStatusNameByStatus(authStatus);
        userInfo.getParam().put("statusString",statusString);
        userInfo.getParam().put("authStatusString",authStatusString);


    }
}
